#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<wait.h>
#include<syslog.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<errno.h>
#include<unistd.h>
#include<string.h>
#define FNAME "/tmp/out"

static	FILE *fp;
static int daemonize(void)
{
	pid_t pid;
	int fd;
	pid=fork();
	if(pid<0)
		return -1;
	if(pid>0)
		exit(0);
	fd=open("/dev/null",O_RDWR);
	if(fd<0)
		return -1;
	dup2(fd,0);
	dup2(fd,1);
	dup2(fd,2);
	if(fd>2)
		close(fd);
	setsid();
	chdir("/");
	return 0;	
}

static void daemon_exit(int s)
{
	fclose(fp);
	closelog;
	return 0;
}



int main()
{
	int i;
	struct sigaction sa;

	sa.sa_handler=daemon_exit;
	sigemptyset(&sa.sa_mask);
	sigaddset(&sa.sa_mask,SIGINT);
	sigaddset(&sa.sa_mask,SIGTERM);
	sigaddset(&sa.sa_mask,SIGQUIT);
	sa.sa_flags=0;

	sigaction(SIGINT,&sa,NULL);
	sigaction(SIGTERM,&sa,NULL);
	sigaciont(SIGQUIT,&sa,NULL);
	openlog("mydaemon",LOG_PID,LOG_DAEMON);
	if(daemonize())
	{	
		syslog(LOG_ERR,"daemonize failed");
		return -1;
	}
	else
	{
		syslog(LOG_INFO,"daemonize success");
	}

	fp=fopen(FNAME,"w");
	if(fp==NULL)
	{
		syslog(LOG_ERR,"file open failed:%s",strerror(errno));
		return -1;
	}
	syslog(LOG_INFO,"%s is opened",FNAME);
	for(i=0;;i++)
	{
		fprintf(fp,"%d\n",i);
		fflush(fp);
		syslog(LOG_DEBUG,"%d is printed",i);
		sleep(1);
	}
//	fclose(fp);
//	closelog();
	return 0;
}

